<?php

namespace App\Admin\Controllers;

use App\Models\User;
use Encore\Admin\Http\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Table;

use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Illuminate\Http\Request;

class UserController extends AdminController
{
    protected $title = '用户';

    /**
     * Make a grid builder.
     *
     * @return Table
     */
    protected function table()
    {
        $table = new Table(new User);

        $table->id('Id');
        $table->key('Key');
        $table->username('用户名');
        $table->name('Name');
        $table->email('Email');
        $table->avatar('Avatar')->display(function () {
            return sprintf(
                '<a href="%s" target="_blank"><img src="%s" style="max-width: 40px;"/></a>',
                attachmentUrl($this->avatar), attachmentUrl($this->avatar, 40, 40)
            );
        });
        $table->point_counts('Point counts');
        $table->created_at('Created at');
        $table->updated_at('Updated at');

        return $table;
    }

    /**
     * Make a show builder.
     *
     * @param mixed   $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(User::findOrFail($id));

        $show->id('Id');
        $show->key('Key');
        $show->name('Name');
        $show->email('Email');
        $show->remember_token('Remember token');
        $show->avatar('Avatar');
        $show->point_count('Point counts');
        $show->topic_count('Topic counts');
        $show->comment_count('Comment counts');
        $show->following_count('Following counts');
        $show->fans_count('Fans counts');
        $show->created_at('Created at');
        $show->updated_at('Updated at');

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new User);

        $form->text('name', 'Name');
        $form->email('email', 'Email');
        $form->password('password', 'Password');
        $form->image('avatar', 'Avatar')->uniqueName();

        $form->hidden('sb')->default(1111);

        return $form;
    }

    public function selectJson(Request $request)
    {
        $q = $request->q;
        if (!$q) {
            return [];
        }
        $NewUsers = User::query()->where("username", "like", "%{$q}%")->paginate(null, ['id', 'username']);

        foreach ($NewUsers as &$NewUser) {
            $NewUser->text = sprintf("%s", $NewUser->username);
        }

        return $NewUsers;
    }
}
